# Create a descriptive plot of emotional reactions on the two parties pages during the 2016 US presidential election (Figure 2).
# Create a descriptive plot of average emotional reactions pooling all the elections (Figure 3).




##############
# r settings #
##############

version
#platform       x86_64-w64-mingw32               
#arch           x86_64                           
#os             mingw32                          
#crt            ucrt                             
#system         x86_64, mingw32                  
#status                                          
#major          4                                
#minor          2.2                              
#year           2022                             
#month          10                               
#day            31                               
#svn rev        83211                            
#language       R                                
#version.string R version 4.2.2 (2022-10-31 ucrt)
#nickname       Innocent and Trusting 

library(brms)
library(ggplot2)
library(ggpubr)
library(stargazer)
library(ggrepel)
library(dplyr)

sessionInfo()
#R version 4.2.2 (2022-10-31 ucrt)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows 10 x64 (build 22631)
#Matrix products: default
#locale:
#[1] LC_COLLATE=English_United States.utf8  LC_CTYPE=English_United States.utf8    LC_MONETARY=English_United States.utf8
#[4] LC_NUMERIC=C                           LC_TIME=English_United States.utf8    
#attached base packages:
#[1] stats     graphics  grDevices utils     datasets  methods   base     
#other attached packages:
#[1] ggrepel_0.9.3   dplyr_1.1.0     stargazer_5.2.3 ggpubr_0.6.0    brms_2.19.0     Rcpp_1.0.8.3    ggplot2_3.4.1  
#loaded via a namespace (and not attached):
#[1] nlme_3.1-160         matrixStats_0.63.0   xts_0.12.2           threejs_0.3.3        rstan_2.26.22       
#[6] tensorA_0.36.2       tools_4.2.2          backports_1.4.1      utf8_1.2.2           R6_2.5.1            
#[11] DT_0.26              colorspace_2.0-3     withr_2.5.0          tidyselect_1.2.0     gridExtra_2.3       
#[16] prettyunits_1.1.1    processx_3.6.1       Brobdingnag_1.2-9    emmeans_1.8.4-1      curl_5.0.2          
#[21] compiler_4.2.2       textshaping_0.3.6    cli_3.6.1            shinyjs_2.1.0        labeling_0.4.2      
#[26] colourpicker_1.2.0   posterior_1.3.1      scales_1.2.0         dygraphs_1.1.1.6     checkmate_2.1.0     
#[31] mvtnorm_1.1-3        callr_3.7.0          StanHeaders_2.26.27  systemfonts_1.0.4    stringr_1.5.0       
#[36] digest_0.6.29        base64enc_0.1-3      pkgconfig_2.0.3      htmltools_0.5.6      fastmap_1.1.0       
#[41] htmlwidgets_1.6.2    rlang_1.1.1          rstudioapi_0.15.0    shiny_1.7.2          farver_2.1.0        
#[46] generics_0.1.2       zoo_1.8-10           jsonlite_1.8.7       crosstalk_1.2.0      gtools_3.9.3        
#[51] car_3.1-0            zip_2.2.0            distributional_0.3.1 inline_0.3.19        magrittr_2.0.3      
#[56] loo_2.5.1            bayesplot_1.10.0     Matrix_1.5-3         munsell_0.5.0        fansi_1.0.3         
#[61] abind_1.4-5          lifecycle_1.0.3      stringi_1.7.8        carData_3.0-5        pkgbuild_1.4.0      
#[66] plyr_1.8.7           grid_4.2.2           parallel_4.2.2       promises_1.2.0.1     crayon_1.5.1        
#[71] miniUI_0.1.1.1       lattice_0.20-45      ps_1.7.1             pillar_1.9.0         igraph_1.3.2        
#[76] ggsignif_0.6.3       estimability_1.4.1   markdown_1.1         shinystan_2.6.0      codetools_0.2-18    
#[81] reshape2_1.4.4       stats4_4.2.2         rstantools_2.2.0     glue_1.6.2           V8_4.3.2            
#[86] RcppParallel_5.1.5   vctrs_0.6.3          httpuv_1.6.5         tidyr_1.3.0          purrr_1.0.1         
#[91] gtable_0.3.0         openxlsx_4.2.5.2     mime_0.12            broom_1.0.5          xtable_1.8-4        
#[96] rstatix_0.7.2        coda_0.19-4          later_1.3.0          ragg_1.2.5           tibble_3.2.1        
#[101] shinythemes_1.2.0    ellipsis_0.3.2       bridgesampling_1.1-2




#############
# load data #
#############

library(brms)
library(ggplot2)
library(ggpubr)
library(stargazer)

load("PSRM Replication Files/PresidentialElectionsPosts.RData")

# focus on 15 days before and after the election
day_range <- 15

sub <- president_df[which(president_df$daysinceelection >= -1*day_range
                          & president_df$daysinceelection <= day_range),]

# winners and losers
winners <- sub[which(sub$win == 1),]
losers <- sub[which(sub$win != 1),]

length(unique(winners$electionname[which(!is.na(winners$polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$economic_polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$social_polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$populist_present))])) # 27
length(unique(winners$electionname[which(!is.na(winners$populist_dummy))])) # 27

length(unique(losers$electionname[which(!is.na(losers$polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$economic_polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$social_polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$populist_present))])) # 27
length(unique(losers$electionname[which(!is.na(losers$populist_dummy))])) # 27




###########
# us 2016 #
###########

us2016 <- president_df[president_df$electionname == "United States_2016",] 

range(us2016$daysinceelection)
table(us2016$yearmonth)
table(us2016$post)

# set colors
us2016$linecol <- "#0015BC"
us2016$linecol[us2016$party_country == "Republican Party_United States"] <- "#E9141D"

us2016$pointcol <- rgb(0/255, 21/255, 188/255, 0.4)
us2016$pointcol[us2016$party_country == "Republican Party_United States"] <- rgb(233/255, 20/255, 29/255, 0.4)

dl <- us2016[us2016$party_country != "Republican Party_United States",
             c("party", "date", "post", "loveprop", "linecol", "pointcol")]
colnames(dl)[4] <- "prop"
dl$type <- paste0("(c) ", dl$party, " + Love")

da <- us2016[us2016$party_country != "Republican Party_United States",
             c("party", "date", "post", "angryprop", "linecol", "pointcol")]
colnames(da)[4] <- "prop"
da$type <- paste0("(d) ", da$party, " + Angry")


rl <- us2016[us2016$party_country == "Republican Party_United States",
             c("party", "date", "post", "loveprop", "linecol", "pointcol")]
colnames(rl)[4] <- "prop"
rl$type <- paste0("(a) ", rl$party, " + Love")

ra <- us2016[us2016$party_country == "Republican Party_United States",
             c("party", "date", "post", "angryprop", "linecol", "pointcol")]
colnames(ra)[4] <- "prop"
ra$type <- paste0("(b) ", ra$party, " + Angry")


usgroup <- rbind(dl, da, rl, ra)
usgroup$type <- factor(usgroup$type, levels=c("(a) Republican Party + Love",
                                              "(b) Republican Party + Angry",
                                              "(c) Democratic Party + Love",
                                              "(d) Democratic Party + Angry"))

# figure 2
ggplot(data = usgroup, 
       aes(x = date, y = prop, group = post, colour=party)) + 
  geom_vline(xintercept = as.Date("2016-11-08"), lty=2) +
  geom_point(aes(shape = "."), size = 0.9) +
  geom_smooth(method = "loess", lwd=1.5, level=0.95, span=1.2) +
  scale_color_manual(values=c("#0015BC", "#E9141D")) +
  facet_wrap(. ~ type, ncol = 2) +
  xlab("Date (7/31/2016-2/16/2017)") + 
  ylab("Reaction Proportion") +
  coord_cartesian(ylim=c(0, 25)) +
  theme_bw() +
  theme(legend.position = "none",
        strip.text.x = element_text(size = 14),
        axis.text.x = element_text(size = 12),
        axis.text.y = element_text(size = 12),
        axis.title.x = element_text(size = 16),
        axis.title.y = element_text(size = 16))

#ggsave("uselection.pdf", width=12, height=6)




############################
# pooled average reactions #
############################

aveposts <- data.frame(Type=rep(c("Winners", "Losers"), each=31),
                       dayssinceelection=-15:15)
aveposts$Type <- factor(aveposts$Type, levels=unique(aveposts$Type))

# compute average number of posts
aveposts$nposts[1:31] <- as.vector(table(winners$daysinceelection) / tapply(winners$party_election, winners$daysinceelection, function(p){
  length(unique(p))
}))

aveposts$nposts[32:62] <- as.vector(table(losers$daysinceelection) / tapply(losers$party_election, losers$daysinceelection, function(p){
  length(unique(p))
}))

# compute average love and angry proportions
aveposts$aveloveprop[1:31] <- tapply(winners$loveprop, winners$daysinceelection, mean)
aveposts$aveloveprop[32:62] <- tapply(losers$loveprop, losers$daysinceelection, mean)
aveposts$aveangryprop[1:31] <- tapply(winners$angryprop, winners$daysinceelection, mean)
aveposts$aveangryprop[32:62] <- tapply(losers$angryprop, losers$daysinceelection, mean)

colnames(aveposts)

al <- aveposts[,c(1,2,4)]
colnames(al)[3] <- "prop"
al$reaction <- "Love"

aa <- aveposts[,c(1,2,5)]
colnames(aa)[3] <- "prop"
aa$reaction <- "Angry"

avela <- rbind(al, aa)

avela$reaction <- factor(avela$reaction, levels=unique(avela$reaction))

avela$reaction2 <- NA
avela$reaction2[which(avela$reaction == "Love")] <- "(a) Love"
avela$reaction2[which(avela$reaction == "Angry")] <- "(b) Angry"

# figure 3
ggplot(data = avela, 
       aes(x = dayssinceelection, y = prop, colour = Type)) +
  facet_wrap(. ~ reaction2, ncol = 2) +
  geom_vline(xintercept=0, lwd=0.5, lty=2) +
  geom_line(lwd = 1.7) +
  scale_color_manual(values=c("black", "gray")) +
  xlab("Days since the Election (±15 Days)") +
  ylab("Reaction Proportion") +
  theme_bw() +
  theme(strip.text.x = element_text(size = 14),
        axis.text.x = element_text(size = 12),
        axis.text.y = element_text(size = 12),
        axis.title.x = element_text(size = 16),
        axis.title.y = element_text(size = 16))

#ggsave("aveprops.pdf", width=12, height=6)
